<?php
namespace app\admin\controller;
use think\Db;
class Category extends Common
{

    //首页分类展示
    public function index()
    {
        $categorys=DB::name('category')->where('pid',0)->order('displayorder desc')->select();
        foreach($categorys as $key=>$value)
        {
            $categorys[$key]['status']=$this->is_show($value['status']);
            $categorys[$key]['is_nav']=$this->is_show($value['is_nav']);
            $categorys[$key]['pname']=$this->getpname($value['pid']);
            $child=DB::name('category')->where('pid',$value['id'])->order('displayorder desc')->select();
            if($child){
                foreach($child as $k=>$v)
                {
                    $child[$k]['status']=$this->is_show($v['status']);
                    $child[$k]['is_nav']=$this->is_show($v['is_nav']);
                    $child[$k]['pname']=$this->getpname($v['pid']);
                    $child[$k]['name']=$v['name'];
                }
                $categorys[$key]['child']=$child;
            }


        }
        $this->assign('categorys',$categorys);
        return $this->fetch();
    }

    //添加/编辑category
    public function postdata()
    {
        if(!request()->isPost()){
            $id=input('id');
            $pid=input('pid');
            if(isset($pid)){
                $this->assign('pid',$pid);
            }
            if(isset($id)){
                $category_info=DB::name('category')->where('id',$id)->find();
                $this->assign('category_info',$category_info);
            }

            $first_category=DB::name('category')->where('pid',0)->select();
            $this->assign('first_category',$first_category);
            return $this->fetch();
        }else{
            $postdata = input('post.');
            isset($postdata['pic']) && $data['pic'] = $postdata['pic'];
            $data['status'] = $postdata['status'];
            $data['displayorder'] = $postdata['displayorder'];
            $data['pid'] = $postdata['pid'];
            $data['name'] = $postdata['name'];
            $data['type'] = $postdata['type'];
            $data['is_nav'] = $postdata['is_nav'];
            if($postdata['id']!=0){
                DB::name('category')->where('id',$postdata['id'])->update($data);
            }else{
                DB::name('category')->insert($data);
            }
            $json = array();
            $json['status'] = '200';
            $json['msg'] = 'ok';
            $json['data'] = $data;
            echo json_encode($json);
        }
    }

    public function del()
    {
        $id=input('id');
        if(!$id){
            $this->ajaxReturn('未检测到分类id');
        }
        $res=DB::name('category')->where('id',$id)->delete();
        if($res){
            $this->ajaxJson('删除成功');
        }
    }
}
